Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

128
Views
JS : console.log displays "undefined" in the end of an array of objects

I wanted to display a simple array's items on the console, using foreach. It dispalys all the items(it's OK), but it displays "cars : undefined" at the end. I dont want to display "cars : undefined", but only the 3 items of the array. How to do ?

var cars = [{
    year: 2011,
    type: "Volvo"
}, {
    year: 1999,
    type: "Volvo"
}, {
    year: 2003,
    type: "Volvo"
}];
console.log("1");

console.log("cars : " + cars.forEach(a => console.log(a)));
console.log("2");

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

forEach() returns undefined. try like this

var cars = [{
    year: 2011,
    type: "Volvo"
}, {
    year: 1999,
    type: "Volvo"
}, {
    year: 2003,
    type: "Volvo"
}];
console.log("1");

console.log("cars : ");
cars.forEach(a => console.log(a))
console.log("2");
about 4 years ago · Juan Pablo Isaza Report

0

console.log outputs a string, but returns undefined. So, the inner one writes your data, returns undefined, and the outer one writes 'cars: undefined'

=> You should produce a string inside the log function, like this :

console.log("cars :" + cars.map(a => ` ${a.type} ${a.year}` ));

That will log:

cars : Volvo 2011, Volvo 1999, Volvo 2003
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!